import requests
import json
import time

url = "https://api.coze.cn/open_api/v2/chat"
headers = {
    "Authorization": "Bearer pat_I5MEIhFAWxp6opxeM7zDeDuty97GJg79HjMR38ORFPJqaILsiOGUYh7wMdOiQXAz",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Host": "api.coze.cn",
    "Connection": "keep-alive"
}

data = {
    "conversation_id": "123",
    "bot_id": "7364382511008415759",
    "user": "29032201862555",
    "query": "你好",
    "stream": True
}

# 记录开始时间
start_time = time.time()

# 设置stream为True，以启用流式传输
response = requests.post(url, headers=headers, json=data, stream=True)

# 初始化一个标志，用于检查是否已接收到第一个数据块
first_chunk_received = False

# 逐块读取数据
for chunk in response.iter_lines():
    if chunk:  # 过滤掉keep-alive的新行
        # 如果是第一个数据块，记录结束时间并打印耗时
        if not first_chunk_received:
            end_time = time.time()
            first_chunk_time = end_time - start_time
            print(f"第一个数据块返回耗时：{first_chunk_time:.4f} 秒")
            first_chunk_received = True
        
        # 打印数据块内容
        print("接收到数据块：", chunk.decode('utf-8'))

# 如果没有接收到任何数据块，则可能请求失败或流为空
if not first_chunk_received:
    print("请求可能失败或没有数据返回。")
